export class Captcha {
    constructor(){
        this._captchaObj = null;
        this._shouldCallCaptcha = false;
        this._onSuccess = null;
        this._onError = null;

        fetch('/user/api/getcode').then((res) => {
            if(res.ok){
                return res.json();
            } else {
                throw '无法访问Api';
            }
        }).then((data) => {
            initGeetest({
                gt: data.gt,
                challenge: data.challenge,
                offline: !data.success,
                new_captcha: true,
                product: 'bind',
            }, (obj) => {
                this._captchaObj = obj;
                if(this._shouldCallCaptcha){ //加载完成后立刻调用
                    this._captchaObj.verify();
                    this._captchaObj.onSuccess(this.buildOnSuccess(this._onSuccess));
                    this._shouldCallCaptcha = false;
                    this._onSuccess = null;
                    this._onError = null;
                }
            })
        });
    }

    verify(){
        return new Promise((resolve, reject) => {
            if(!this._captchaObj){
                this._shouldCallCaptcha = true;
                this._onSuccess = resolve;
                this._onError = reject;
            } else { //已经加载成功的情况，直接调用
                this._captchaObj.verify();
                this._captchaObj.onSuccess(this.buildOnSuccess(resolve));
                this._captchaObj.onError((err) => {
                    $.toaster({
                        priority: 'danger',
                        title: '错误',
                        message: '无法加载验证码，请刷新重试',
                        settings: {
                            timeout: 100000,
                        },
                    });
                    reject('error', err);
                });

                this._captchaObj.onClose(() => {
                    reject('close');
                });
            }
        });
    }

    buildOnSuccess(callback){
        return (function(){
            var result = this._captchaObj.getValidate();
            callback(result);
            this._captchaObj.reset();
        }).bind(this);
    }
}